<template>
  <div class="panel">
    <el-button @click="addRiver_canvas">canvas渲染</el-button>
  </div>

  <simple-time-line @change="updateRiver" />

  <base-map />
</template>
<script setup>
import { onMounted, nextTick, ref, watchEffect, watch } from "vue";

import { Map, View } from "ol";
import { fromLonLat, get, transform } from "ol/proj";
import { Vector as VectorLayer, Image as ImageLayer } from "ol/layer";
import { Vector as VectorSource, ImageCanvas } from "ol/source";
import Feature from "ol/feature";
import { Point, LineString, Polygon, Circle } from "ol/geom";
import {
  Style,
  Stroke,
  Fill,
  Circle as CircleStyle,
  Icon,
  Text,
} from "ol/style";

import GeoJSON from "ol/format/GeoJSON.js";
import Select from "ol/interaction/Select.js";

import * as turf from "@turf/turf";
import * as radash from "radash";

import { getLayerByName, getVectorLayer } from "@/utils/layer.js";
import { flyTo, flyToFeature, getExtent } from "../../utils/view";

import BJGrid from "@/data/河流三角网/BJ.json";

import SimpleTimeLine from "@/components/SimpleTimeLine.vue";
import BaseMap from "@/components/BaseMap.vue";

let riverMeshFeatures, riverShadowLayer, riverCanvasLayer;

// canvas渲染
function addRiver_canvas() {
  // 读取GeoJSON数据
  riverMeshFeatures = new GeoJSON().readFeatures(BJGrid, {
    dataProjection: "EPSG:4547",
    featureProjection: "EPSG:4326",
  });

  addColor();

  // 添加网格的点击交互事件
  // window.map.on("click", handleCellClick);

  addShadowLayer();

  // 获取地图的像素尺寸
  const mapSize = window.map.getSize();

  // 使用canvas渲染
  riverCanvasLayer = new ImageLayer({
    properties: {
      name: "riverLayer_canvas",
    },
    zIndex: 1,
    source: new ImageCanvas({
      canvasFunction: (
        _extent,
        _resolution,
        _pixelRatio,
        size,
        _projection
      ) => {
        // 创建画布
        const canvas = document.createElement("canvas");
        const ctx = canvas.getContext("2d");

        // 设置画布大小
        canvas.width = size[0];
        canvas.height = size[1];

        // 计算缩放比例
        const ratio = mapSize[0] / size[0];
        // 设置字体
        ctx.font = "60px Arial";

        const features = riverMeshFeatures;

        // 遍历要素，绘制
        features.forEach(feature => {
          // 每个格子设置颜色
          const color = feature.get("color") || "#00008B";

          // 几何要素
          let coordinates = feature.getGeometry().getCoordinates()[0][0];

          // 开始绘制路径
          ctx.beginPath();
          // 遍历环中的每个点并绘制格子
          let pixel = [0, 0];

          coordinates.forEach((point, index) => {
            // 未转比例的坐标
            const unconvertPixel = window.map.getPixelFromCoordinate(point);
            // 转比例坐标
            pixel = [unconvertPixel[0] / ratio, unconvertPixel[1] / ratio];
            if (index === 0) {
              // 将绘制起点移动到第一个点
              ctx.moveTo(pixel[0], pixel[1]);
            } else if (index === coordinates.length - 1) {
              // 绘制闭合路径
              ctx.closePath();
            } else {
              // 绘制线段到下一个点
              ctx.lineTo(pixel[0], pixel[1]);
            }
          });

          ctx.fillStyle = color;
          ctx.fill();
          // ctx.strokeStyle = "black";
          // ctx.lineWidth = 1;
          // ctx.stroke();
        });

        return canvas;
      },
      projection: "EPSG:4326",
      ratio: 1,
      interpolate: true,
    }),
  });

  window.map.addLayer(riverCanvasLayer);
}

function downloadImg(canvas, fileName) {
  const imgUrl = canvas.toDataURL("image/jpg");

  const a = document.createElement("a");
  a.download = fileName || "canvas图片";
  a.href = imgUrl;

  a.click();
}

// 点击交互事件处理函数
function handleCellClick(event) {
  const coordinate = event.coordinate;
  let clickedFeature;

  const { length } = riverMeshFeatures;
  let index = 0;

  while (!clickedFeature && index < length) {
    const feature = riverMeshFeatures[index];
    const geometry = feature.getGeometry();
    if (geometry.intersectsCoordinate(coordinate)) {
      clickedFeature = feature;
    }
    index++;
  }

  console.log("点击事件", "网格" + index, clickedFeature);
}

// 添加遮罩图层（实现事件交互）
function addShadowLayer() {
  // 创建矢量图层
  riverShadowLayer = getVectorLayer({
    map: window.map,
    layerName: "riverLayer_shadow",
    style: new Style({
      fill: new Fill({
        color: "red",
      }),
      stroke: new Stroke({
        color: "black",
        width: 1,
      }),
    }),
    zIndex: 2,
  });

  riverShadowLayer.getSource().addFeatures(riverMeshFeatures);

  // 禁止矢量图层渲染
  riverShadowLayer.setVisible(false);

  // 点击位置查询
  // window.map.on("click", event => {
  //   const pixel = event.pixel;
  //   const features = window.map.getFeaturesAtPixel(pixel);
  //   console.log("点击事件", pixel, features);
  //   if (features.length > 0) {
  //     const feature = features[0];

  //     const properties = feature.getProperties();
  //     console.log(properties);
  //   }
  // });

  // select交互查询
  // var selectClick = new Select();
  // window.map.addInteraction(selectClick);
  // selectClick.on("select", function (e) {
  //   var features = e.target.getFeatures().getArray();
  //   console.log("选择事件", features);
  // });

  // 空间查询

  window.map.on("click", event => {
    const pixel = event.pixel;
    const extent = new Point(
      window.map.getCoordinateFromPixel(pixel)
    ).getExtent();
    const features = [];
    riverShadowLayer
      .getSource()
      .forEachFeatureIntersectingExtent(extent, feature => {
        features.push(feature);
      });
    console.log("点击事件", pixel, features);
    if (features.length > 0) {
      const feature = features[0];

      const properties = feature.getProperties();
      // console.log(properties);
    }
  });
}

// 给图形添加颜色
function addColor(index) {
  if (!riverMeshFeatures) return;
  const colorBand = [
    "#ff0000",
    "#ff7f00",
    "#ffff00",
    "#7fff00",
    "#00ff00",
    "#00ff7f",
    "#00ffff",
    "#007fff",
    "#0000ff",
    "#7f00ff",
    "#ff00ff",
    "#ff007f",
  ];

  const color = colorBand[index % colorBand.length];
  riverMeshFeatures.forEach((feature, index) => {
    feature.set("color", color);
  });
}

// 更新河道颜色
async function updateRiver(index) {
  //   fadeOut();
  addColor(index);
  // 刷新canvas渲染
  riverCanvasLayer.getSource().changed();

  await radash.sleep(1000);
  //   fadeIn();
}
</script>

<style lang="less" scoped>
#mapContainer {
  width: 100%;
  height: 99vh;
}

.panel {
  position: absolute;
  top: 10px;
  left: 150px;
  z-index: 999;
}
</style>
